Type conversion is the process of converting data from one type to another. JavaScript performs type conversion in two ways: implicitly (automatic) and explicitly (manual).
JavaScript automatically converts data types when necessary. This is known as implicit conversion or type coercion.
console.log("5" - 3); // 2 (string "5" is converted to number 5)
console.log("5" + 3); // "53" (number 3 is converted to string "3")
Explicit conversion is when you manually convert data from one type to another using built-in methods.
let num = Number("123"); // 123
let floatNum = parseFloat("3.14"); // 3.14
let intNum = parseInt("42"); // 42
let str = String(123); // "123"
let str2 = (456).toString(); // "456"
let bool1 = Boolean(1); // true
let bool2 = Boolean(0); // false
let bool3 = Boolean("hello"); // true
let bool4 = Boolean(""); // false
Here are some examples of type conversion in JavaScript:
console.log(Number("123")); // 123
console.log(String(123)); // "123"
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean("hello")); // true
For more detailed information, you can check out resources like W3Schools and JavaScript.info.